package com.ludomancy.sora;


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.Iterator;

import com.ludomancy.gamelib.Widget;

public class MainWidget extends Widget
{
	public MainWidget(Widget parent, Rectangle area)
	{
		super(parent, area);
	}
		
	public void update()
	{
		if(Game.game != null)
		{
			Game.game.update();
		}
	}
	
	public double[] screenToWorld(int x, int y)
	{
		double[] ret = new double[2];
		ret[0] = (double)x / (double)getWidth();
		ret[1] = (double)y / (double)getHeight();
		return ret;
	}
	
	public int[] worldToScreen(double x, double y)
	{
		int[] ret = new int[2];
		ret[0] = (int)Math.round(x*(double)getWidth()); 
		ret[1] = (int)Math.round(y*(double)getHeight());
		return ret;
	}
	
	public void paint(Graphics g)
	{
		g.setColor(Color.LIGHT_GRAY);
		g.fillRect(0, 0, getWidth(), getHeight());
		
		// paint arrows
		g.setColor(new Color(0xB08319));
		Graphics2D g2d = (Graphics2D)g;
		g2d.setStroke(new BasicStroke(3.0f));
		for (Iterator iter = Game.game.edges.iterator(); iter.hasNext();)
		{
			Edge e = (Edge) iter.next();
			int[] segment1 = worldToScreen(e.v1.px, e.v1.py);
			int[] segment2 = worldToScreen(e.v2.px, e.v2.py);
			g.setColor(new Color(0xB08319));
			g.drawLine(segment1[0], segment1[1], segment2[0], segment2[1]);
			g.setColor(Color.RED);
//			for (int i = 0; i < 15; i++)
//			{
//				double t = (double)i/(double)15;
//				int[] p = worldToScreen(e.getPositionAtPoint(t)[0], e.getPositionAtPoint(t)[1]);
//				g.drawLine(p[0], p[1], p[0]+(int)(e.getVelocityAtPoint(t)[0]*100000), p[1]+(int)(e.getVelocityAtPoint(t)[1]*100000));
//				int[] vel1 = worldToScreen(e.v1.velX(), e.v1.velY());
//				int[] vel2 = worldToScreen(e.v2.velX(), e.v2.velY());
//				g.drawLine(segment1[0], segment1[1], segment1[0]+(int)(e.v1.velX()*100000), segment1[1]+(int)(e.v1.velY()*100000));
//				g.drawLine(segment2[0], segment2[1], segment2[0]+(int)(e.v2.velX()*100000), segment2[1]+(int)(e.v2.velY()*100000));
//			}
		}
		
		// paint character
		int[] pos = worldToScreen(Game.game.px, Game.game.py);
		int diameter = worldToScreen(Game.game.radii*2, 0)[0];
		g.setColor(Color.BLACK);
		g.fillOval(pos[0]-diameter/2, pos[1]-diameter/2, diameter, diameter);
	}
	
	public void mouseMoved(Point point)
	{
		super.mouseMoved(point);
		double[] newPos = screenToWorld(point.x, point.y);
		Game.game.setTarget(newPos[0], newPos[1]);
	}

}
